import { createSignal } from "solid-js";
import Card from "../components/Card";
import { useCartContext } from "../context/CartContext";


export default function Cart(){
    const { items, setItems } = useCartContext();

    const decrement = (id) => {
        if(items.find(p => p.id === id).quantity > 1)
            setItems(p => p.id === id, "quantity", q => q - 1)
    }
    const increment = (id) => {
        setItems(p => p.id === id, "quantity", q => q + 1)
    }

    const total = () => {
        return items.reduce((acc, p) => {
            return acc + p.quantity * p.price
          }, 0)
    }
    return(
        <div class="max-w-md my-8 mx-auto">
            <Card rounded={true}>
                <h2>Your Shopping Cart</h2>
                <div class="grid grid-cols-2">
                    <For each={items}>
                        {item => (
                            <>
                                <div class="col-end-1 my-6">
                                    <p class=" inline-block">{item.title} - {item.price}$ x {item.quantity} </p>
                                </div>
                                <span class="col-end-2 mx-4 my-3 py-2 bg-amber-400 w-max rounded-md shadow-md">
                                    <button class="px-3 text-bold text-xl" onClick={() => decrement(item.id)}>-</button>
                                    <p class="px-2 border-x-2 text-bold text-xl border-amber-500 inline-block">{item.quantity}</p>
                                    <button class="pr-3 pl-2 text-bold text-xl" onClick={() => increment(item.id)}>+</button>
                                </span>
                            </>
                            
                        )}
                    </For>
                </div>

                <p class="mt-8 pt-8 border-t-2 font-bold">Total price: {total()}$</p>
            </Card>
        </div>
    );
} 